import axios, { InternalAxiosRequestConfig } from "axios";
const myAxios = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 10000,
  withCredentials: true,
});

myAxios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

myAxios.interceptors.response.use(
  function (response) {
    console.log(response);
    const { data } = response;
    console.log(data);

    if (data.code === 40100) {
      const isCurrentUserRequest =
        response.config.url?.includes("user/current");
      const isLoginPage = window.location.pathname.startsWith("/user/login");

      if (!isCurrentUserRequest && !isLoginPage) {
        localStorage.removeItem("token"); // 清除 Token（可选）
        window.location.href = `/user/login?redirect=${encodeURIComponent(
          window.location.href
        )}`;
        return Promise.reject(new Error("Unauthorized"));
      }
    }

    return response;
  },
  function (error) {
    return Promise.reject(error);
  }
); // 注意结尾符号

export default myAxios;
